/*
 * Copyright (C) 2015 The Sven Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.core.exception;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import cc.core.util.LogUtil;

/**
 * 作者：helloTan on 15/7/1 12:27
 * 邮箱：hellotanm@gmail.com
 */
public class HandlerUnException implements UncaughtExceptionHandler {

    private static HandlerUnException self;

    private Context context;
    private DateFormat formatter;
    private ArrayList<UnExceptionListener> unExceptionListeners;
    private Map<String, String> exInfo = new HashMap<>();
    private Thread.UncaughtExceptionHandler defaultHandler;

    private HandlerUnException() {
    }

    public static HandlerUnException getInstance() {
        if (self == null) {
            self = new HandlerUnException();
        }
        return self;
    }

    public void init(Context context) {
        this.context = context;
        this.unExceptionListeners = new ArrayList<>();
        this.formatter = SimpleDateFormat.getDateTimeInstance(); //yyyy-MM-dd-HH-mm-ss
        this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); //获取系统默认的UncaughtException处理器
        Thread.setDefaultUncaughtExceptionHandler(this); //设置该CrashHandler为程序的默认处理器
    }

    public void addUnExceptionListener(UnExceptionListener unExceptionListener) {

        if (unExceptionListener == null) {
            return;
        }

        if (this.unExceptionListeners.isEmpty()) {

            this.addUnExceptionListener(unExceptionListener);

        } else {
            for (UnExceptionListener ue : this.unExceptionListeners) {
                if (ue == unExceptionListener) {
                    return;
                }
                this.unExceptionListeners.add(unExceptionListener);
            }
        }
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && defaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            defaultHandler.uncaughtException(thread, ex);
        } else {

            boolean ret = true;
            for (UnExceptionListener unExceptionListener : this.unExceptionListeners) {
                if (unExceptionListener != null) {
                    ret = unExceptionListener.onExit();
                }
            }

            if (!ret) {
                return;
            }

            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    Toast.makeText(context, "很抱歉, 程序出现异常, 即将退出.", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }.start();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                LogUtil.e("error : ", e);
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex Throwable
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        collectDeviceInfo(context); //收集设备参数信息
        saveCrashInfo2File(ex); //保存日志文件

        return true;
    }

    /**
     * 收集设备参数信息
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                exInfo.put("versionName", versionName);
                exInfo.put("versionCode", versionCode);
            }
        } catch (NameNotFoundException e) {
            LogUtil.e("an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                exInfo.put(field.getName(), field.get(null).toString());
                LogUtil.d(field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                LogUtil.e("an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex Throwable
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {

        String s = "";
        for (Map.Entry<String, String> entry : exInfo.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            s += (key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        s += result;
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = "/sdcard/crash/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(s.getBytes());
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
            LogUtil.e("an error occured while writing file...", e);
        }
        return null;
    }
}
